package cn.seaboot.admin.user.authority;

import cn.seaboot.admin.logger.bean.LogType;
import cn.seaboot.admin.logger.manager.ActionLogger;
import cn.seaboot.admin.mvc.Result;
import cn.seaboot.admin.mvc.SystemConstant;
import cn.seaboot.admin.mvc.argument.Params;
import cn.seaboot.admin.user.bean.Menu;
import cn.seaboot.admin.user.context.UserContext;
import cn.seaboot.admin.user.service.MenuService;
import cn.seaboot.commons.core.CommonUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 菜单权限相关的代码
 *
 * <p>@author Mr.css on 2018-6-20
 */
@Controller
@RequestMapping("authority/menu")
@Tag(name = "系统菜单 [t_sys_menu] 管理")
public class MenuAuthorityCtrl {

    @Resource
    private MenuService menuService;

    @Resource
    private UserContext userContext;

    /**
     * 分配菜单权限
     */
    @ResponseBody
    @Operation(description = "保存菜单权限配置")
    @Parameters({
            @Parameter(name = "ids", description = "菜单ID列表"),
            @Parameter(name = "roleId", description = "角色ID"),
            @Parameter(name = "names", description = "菜单名称", required = false)})
    @RequestMapping(value = "grant", method = RequestMethod.POST)
    @ActionLogger(type = LogType.USER, operation = "分配菜单权限：${names}", exclusive = "names")
    public Result grantMenus(@Params String ids, @Params String roleId, String names) {
        return menuService.grantMenus(ids, roleId, names);
    }

    /**
     * 查询登录用户的菜单栏
     */
    @ResponseBody
    @Operation(description = "查询首页菜单")
    @Parameters({
            @Parameter(name = "groupName", description = "组别", required = false)
    })
    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public List<Map<String, Object>> selectMenuAuthority(
            @RequestParam(defaultValue = SystemConstant.PROJECT_ID) String groupName) {
        return menuService.queryMenuAuthority(groupName, userContext.getUserDept().getRoleId());
    }

    /**
     * 查询可分配菜单
     */
    @ResponseBody
    @Operation(description = "查询角色所拥有的的菜单权限", parameters = {@Parameter(name = "id", description = "角色ID")})
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public List<Menu> queryMenus(
            @RequestParam(defaultValue = SystemConstant.PROJECT_ID) String groupName,
            String roleId) {
        if (CommonUtils.isEmpty(roleId)) {
            roleId = userContext.getUserDept().getRoleId();
        }
        return menuService.selectMenuByRoleId(groupName, roleId);
    }
}
